<template>
  <div class="blockchain-container">
    <div class="overview-section">
      <div class="overview-header">
        <div class="title-area">
          <h2>区块链概览</h2>
          <div class="subtitle">Blockchain Overview</div>
        </div>
        <el-button type="primary" class="refresh-btn" @click="refreshData">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
      </div>
      
      <div class="overview-cards">
        <div class="stat-card total-blocks">
          <div class="icon-bg">
            <el-icon><Connection /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value">{{ blockchainData.blocks?.length || 0 }}</div>
            <div class="stat-label">总区块数</div>
            <div class="stat-subtitle">Total Blocks</div>
          </div>
        </div>

        <div class="stat-card latest-time">
          <div class="icon-bg">
            <el-icon><Timer /></el-icon>
          </div>
          <div class="stat-content">
            <div class="stat-value time">{{ formatDate(getLatestBlockTime()) }}</div>
            <div class="stat-label">最新区块时间</div>
            <div class="stat-subtitle">Latest Block Time</div>
          </div>
        </div>
      </div>
    </div>

    <!-- 区块列表 -->
    <el-col :span="24" class="mt-4">
      <el-card>
        <template #header>
          <div class="card-header">
            <h3>区块列表</h3>
          </div>
        </template>
        
        <div class="blockchain-list">
          <div v-for="(block, index) in blockchainData.blocks" :key="block.hash" class="block-item">
            <el-card 
              :class="['block-card', {'genesis-block': index === 0}]"
              shadow="hover"
            >
              <div class="block-header">
                <span class="block-index">区块 #{{ index }}</span>
                <el-tag 
                  :type="index === 0 ? 'danger' : 'success'"
                  size="small"
                >
                  {{ index === 0 ? '创世区块' : '数据区块' }}
                </el-tag>
              </div>

              <div class="block-content">
                <div class="block-info">
                  <div class="info-item">
                    <span class="label">区块哈希：</span>
                    <div class="hash-container">
                      <span class="hash" @click="copyToClipboard(block.hash)">
                        {{ formatHash(block.hash) }}
                      </span>
                      <el-tooltip content="复制哈希值" placement="top" :hide-after="1500">
                        <el-icon class="copy-icon" @click="copyToClipboard(block.hash)"><CopyDocument /></el-icon>
                      </el-tooltip>
                    </div>
                  </div>
                  <div class="info-item">
                    <span class="label">前块哈希：</span>
                    <div class="hash-container">
                      <span class="hash" @click="copyToClipboard(block.previousHash)">
                        {{ formatHash(block.previousHash) }}
                      </span>
                      <el-tooltip content="复制哈希值" placement="top" :hide-after="1500">
                        <el-icon class="copy-icon" @click="copyToClipboard(block.previousHash)"><CopyDocument /></el-icon>
                      </el-tooltip>
                    </div>
                  </div>
                  <div class="info-item">
                    <span class="label">时间戳：</span>
                    <span>{{ formatDate(block.timestamp) }}</span>
                  </div>
                  <div class="info-item">
                    <span class="label">随机数：</span>
                    <span>{{ block.nonce }}</span>
                  </div>
                </div>

                <div class="block-data">
                  <div class="data-header">
                    <span>区块数据</span>
                    <el-button 
                      type="primary" 
                      link 
                      @click="showBlockDetails(block)"
                    >
                      查看详情
                    </el-button>
                  </div>
                  <div class="data-preview">
                    {{ getDataPreview(block.data) }}
                  </div>
                </div>
              </div>
            </el-card>
          </div>
        </div>
      </el-card>
    </el-col>

    <!-- 区块详情弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="区块详情"
      width="70%"
      class="block-details-dialog"
      :destroy-on-close="true"
      :close-on-click-modal="false"
    >
      <div v-if="selectedBlock" class="block-details">
        <el-descriptions :column="1" border size="small">
          <el-descriptions-item label="区块哈希">
            <div class="details-hash-container">
              <span class="details-hash">{{ selectedBlock.hash }}</span>
              <el-tooltip content="复制哈希值" placement="top" :hide-after="1500">
                <el-icon class="copy-icon" @click="copyToClipboard(selectedBlock.hash)"><CopyDocument /></el-icon>
              </el-tooltip>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="前块哈希">
            <div class="details-hash-container">
              <span class="details-hash">{{ selectedBlock.previousHash }}</span>
              <el-tooltip content="复制哈希值" placement="top" :hide-after="1500">
                <el-icon class="copy-icon" @click="copyToClipboard(selectedBlock.previousHash)"><CopyDocument /></el-icon>
              </el-tooltip>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="时间戳">
            {{ formatDate(selectedBlock.timestamp) }}
          </el-descriptions-item>
          <el-descriptions-item label="随机数">
            {{ selectedBlock.nonce }}
          </el-descriptions-item>
        </el-descriptions>

        <div class="data-section">
          <h4>区块数据</h4>
          <div v-if="isGenesisBlock(selectedBlock)" class="genesis-data">
            {{ selectedBlock.data[0] }}
          </div>
          <el-table
            v-else
            :data="parseBlockData(selectedBlock.data[0])"
            style="width: 100%"
            border
            size="small"
            :max-height="350"
          >
            <el-table-column prop="id" label="ID" width="60" />
            <el-table-column prop="employeeNo" label="员工编号" width="100" />
            <el-table-column prop="checkTime" label="打卡时间" width="150">
              <template #default="{ row }">
                {{ formatDate(row.checkTime) }}
              </template>
            </el-table-column>
            <el-table-column prop="checkType" label="打卡类型" width="90">
              <template #default="{ row }">
                <el-tag size="small" :type="getCheckTypeTagType(row.checkType)">
                  {{ getCheckTypeText(row.checkType) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="location" label="位置信息" min-width="120" show-overflow-tooltip />
            <el-table-column prop="remark" label="备注" min-width="100" show-overflow-tooltip />
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh, Connection, Timer, CopyDocument } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { getBlockchainData } from '@/api/admin/Blockchain'
const blockchainData = ref({ blocks: [] })
const dialogVisible = ref(false)
const selectedBlock = ref(null)

// 获取区块链数据
const fetchBlockchainData = async () => {
  try {
    const { data } = await getBlockchainData()
    if (data.success) {
      blockchainData.value = data
    }
  } catch (error) {
    console.error('获取区块链数据失败:', error)
    ElMessage.error('获取区块链数据失败')
  }
}

// 刷新数据
const refreshData = () => {
  fetchBlockchainData()
}

// 复制哈希值到剪贴板
const copyToClipboard = (text) => {
  navigator.clipboard.writeText(text)
    .then(() => {
      ElMessage.success('哈希值已复制到剪贴板')
    })
    .catch(() => {
      ElMessage.error('复制失败')
    })
}

// 格式化哈希值显示
const formatHash = (hash) => {
  if (!hash) return '-'
  return hash  // 返回完整哈希值，不再截断
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 获取最新区块时间
const getLatestBlockTime = () => {
  const blocks = blockchainData.value.blocks
  if (!blocks || blocks.length === 0) return null
  return blocks[blocks.length - 1].timestamp
}

// 获取数据预览
const getDataPreview = (data) => {
  if (!data || data.length === 0) return '无数据'
  if (typeof data[0] === 'string' && data[0].startsWith('创世区块')) return data[0]
  try {
    const parsedData = JSON.parse(data[0])
    return `包含 ${parsedData.length} 条考勤记录`
  } catch (e) {
    return '数据解析失败'
  }
}

// 解析区块数据
const parseBlockData = (dataStr) => {
  if (!dataStr) return []
  try {
    if (typeof dataStr === 'string' && dataStr.startsWith('创世区块')) {
      return [{ id: 0, data: dataStr }]
    }
    return JSON.parse(dataStr)
  } catch (e) {
    console.error('解析区块数据失败:', e)
    return []
  }
}

// 显示区块详情
const showBlockDetails = (block) => {
  selectedBlock.value = block
  dialogVisible.value = true
}

// 判断是否为创世区块
const isGenesisBlock = (block) => {
  return block.previousHash === "0"
}

// 获取考勤类型标签类型
const getCheckTypeTagType = (type) => {
  return type === 1 ? 'success' : 'warning'
}

// 获取考勤类型文本
const getCheckTypeText = (type) => {
  return type === 1 ? '上班打卡' : '下班打卡'
}

onMounted(() => {
  fetchBlockchainData()
})
</script>

<style scoped lang="scss">
.blockchain-container {
  padding: 20px;

  .overview-section {
    background: linear-gradient(135deg, #d4eaf7 0%, #a5d3ed 100%);
    border-radius: 15px;
    padding: 25px;
    color: #2c3e50;
    margin-bottom: 30px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);

    .overview-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 25px;

      .title-area {
        h2 {
          margin: 0;
          font-size: 24px;
          font-weight: 600;
          background: linear-gradient(120deg, #2c3e50, #34495e);
          -webkit-background-clip: text;
          -webkit-text-fill-color: transparent;
        }

        .subtitle {
          font-size: 14px;
          color: #486683;
          margin-top: 4px;
        }
      }

      .refresh-btn {
        background: rgba(255, 255, 255, 0.25);
        border: 1px solid rgba(255, 255, 255, 0.3);
        backdrop-filter: blur(5px);
        color: #2c3e50;
        
        &:hover {
          background: rgba(255, 255, 255, 0.35);
        }
      }
    }

    .overview-cards {
      display: flex;
      gap: 20px;
      flex-wrap: wrap;

      .stat-card {
        flex: 1;
        min-width: 250px;
        background: rgba(255, 255, 255, 0.25);
        border-radius: 12px;
        padding: 20px;
        display: flex;
        align-items: center;
        gap: 20px;
        backdrop-filter: blur(5px);
        border: 1px solid rgba(255, 255, 255, 0.3);
        transition: all 0.3s ease;
        color: #2c3e50;

        &:hover {
          transform: translateY(-5px);
          box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
        }

        .icon-bg {
          width: 60px;
          height: 60px;
          border-radius: 12px;
          background: rgba(255, 255, 255, 0.35);
          display: flex;
          align-items: center;
          justify-content: center;

          .el-icon {
            font-size: 30px;
            color: #2c3e50;
          }
        }

        .stat-content {
          flex: 1;

          .stat-value {
            font-size: 28px;
            font-weight: 600;
            margin-bottom: 5px;
            color: #2c3e50;
            
            &.time {
              font-size: 20px;
            }
          }

          .stat-label {
            font-size: 16px;
            color: #486683;
            margin-bottom: 2px;
          }

          .stat-subtitle {
            font-size: 12px;
            color: #6c8094;
          }
        }

        &.total-blocks {
          background: linear-gradient(135deg, rgba(212, 234, 247, 0.4), rgba(212, 234, 247, 0.2));
        }

        &.latest-time {
          background: linear-gradient(135deg, rgba(165, 211, 237, 0.4), rgba(165, 211, 237, 0.2));
        }
      }
    }
  }

  .block-card {
    margin-bottom: 20px;
    border-left: 4px solid #409eff;

    &.genesis-block {
      border-left-color: #f56c6c;
    }

    .block-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 16px;

      .block-index {
        font-size: 16px;
        font-weight: bold;
        color: #303133;
      }
    }

    .block-content {
      .block-info {
        margin-bottom: 16px;

        .info-item {
          margin-bottom: 8px;
          display: flex;
          align-items: flex-start;
          flex-wrap: wrap;
          
          @media screen and (max-width: 768px) {
            flex-direction: column;
            
            .label {
              width: 100% !important;
              margin-bottom: 4px;
            }
            
            .hash-container {
              max-width: 100% !important;
            }
          }

          .label {
            color: #909399;
            width: 100px;
            flex-shrink: 0;
          }

          .hash-container {
            display: flex;
            align-items: center;
            flex: 1;
            background: rgba(64, 158, 255, 0.08);
            border-radius: 4px;
            padding: 6px 10px;
            transition: all 0.3s;
            position: relative;
            max-width: calc(100% - 100px);  // 限制最大宽度
            
            &:hover {
              background: rgba(64, 158, 255, 0.15);
              box-shadow: 0 2px 12px rgba(0, 123, 255, 0.15);
            }
            
            .hash {
              font-family: 'Consolas', monospace;
              font-weight: 500;
              font-size: 13px;
              letter-spacing: 0px;
              color: #409eff;
              word-break: break-all;
              flex: 1;
              cursor: pointer;
              transition: all 0.2s;
              overflow-x: auto;   // 允许水平滚动
              white-space: nowrap; // 保持单行显示
              text-overflow: ellipsis; // 超出部分显示省略号
              padding-right: 4px;  // 为滚动条留出空间
              
              &:hover {
                color: #1867c0;
              }
              
              // 隐藏滚动条但保留功能
              &::-webkit-scrollbar {
                height: 3px;
              }
              
              &::-webkit-scrollbar-thumb {
                background: #409eff;
                border-radius: 3px;
              }
            }
            
            .copy-icon {
              color: #a0cfff;
              cursor: pointer;
              margin-left: 8px;
              font-size: 16px;
              transition: all 0.2s;
              flex-shrink: 0;
              
              &:hover {
                color: #409eff;
                transform: scale(1.2);
              }
            }
          }
        }
      }

      .block-data {
        background: #f5f7fa;
        padding: 12px;
        border-radius: 4px;

        .data-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 8px;
          
          span {
            color: #606266;
            font-weight: bold;
          }
        }

        .data-preview {
          color: #909399;
          font-size: 14px;
        }
      }
    }
  }
}

.block-details-dialog {
  :deep(.el-dialog__header) {
    padding: 15px 20px;
    margin: 0;
    border-bottom: 1px solid #f0f0f0;
    
    .el-dialog__title {
      font-size: 16px;
      font-weight: 600;
    }
  }
  
  :deep(.el-dialog__body) {
    padding: 15px;
  }
  
  .block-details {
    :deep(.el-descriptions__label) {
      width: 80px;
      text-align: right;
      padding-right: 16px;
      color: #606266;
      font-weight: 500;
      font-size: 14px;
    }
    
    :deep(.el-descriptions__content) {
      padding: 6px 10px;
      font-size: 14px;
    }
    
    .details-hash-container {
      display: flex;
      align-items: center;
      background: rgba(64, 158, 255, 0.06);
      border-radius: 4px;
      padding: 6px 10px;
      transition: all 0.3s;
      
      &:hover {
        background: rgba(64, 158, 255, 0.12);
        box-shadow: 0 2px 12px rgba(0, 123, 255, 0.1);
      }
      
      .details-hash {
        font-family: 'Consolas', monospace;
        font-weight: 500;
        font-size: 13px;
        letter-spacing: 0;
        color: #409eff;
        word-break: break-all;
        flex: 1;
        white-space: nowrap;
        overflow-x: auto;
        
        &::-webkit-scrollbar {
          height: 3px;
        }
        
        &::-webkit-scrollbar-thumb {
          background: #409eff;
          border-radius: 3px;
        }
      }
      
      .copy-icon {
        color: #a0cfff;
        cursor: pointer;
        margin-left: 12px;
        font-size: 16px;
        transition: all 0.2s;
        flex-shrink: 0;
        
        &:hover {
          color: #409eff;
          transform: scale(1.2);
        }
      }
    }

    .data-section {
      margin-top: 15px;

      h4 {
        margin: 0 0 10px 0;
        color: #303133;
        font-size: 15px;
        display: flex;
        align-items: center;
        
        &::before {
          content: '';
          display: inline-block;
          width: 3px;
          height: 14px;
          background-color: #409eff;
          margin-right: 8px;
          border-radius: 2px;
        }
      }

      .genesis-data {
        padding: 12px;
        background: #f5f7fa;
        border-radius: 4px;
        color: #606266;
        font-size: 14px;
      }
      
      :deep(.el-table) {
        .el-table__header-wrapper th {
          background-color: #f5f7fa;
          font-size: 13px;
          padding: 6px 0;
          color: #606266;
        }
        
        .el-table__cell {
          padding: 4px 0;
          font-size: 13px;
        }
      }
    }
  }
}

.mt-4 {
  margin-top: 16px;
}
</style> 